package com.engineering.elink.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.engineering.elink.common.ResultType;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * service程序返回的信息格式统一为： { code:0, //状态码,参见Error类 msg :"" //提示信息 data:{} //数据内容 }
 *
 */
public class JSONUtil {
	/**
	 * 生成返回值
	 * 
	 * @param e
	 *            状态和信息
	 * @param data
	 *            返回数据
	 * @return
	 */
	public static Map<String, Object> getJSON(ResultType e, Object data) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", e.getCode());
		map.put("msg", e.getMsg());
		map.put("data", data);
		// return
		// JSONObject.toJSONStringWithDateFormat(map,Constant.DATE_FORMAT,
		// SerializerFeature.WriteMapNullValue);
		return map;
	}

	/**
	 * 重载方法,在无返回数据时使用
	 * 
	 * @param e
	 * @return
	 */
	public static Map<String, Object> getJSON(ResultType e) {
		return getJSON(e, null);
	}

	public static String mapToString(Map<?, ?> map) {
		ObjectMapper mapper = new ObjectMapper();
		String str = "";
		try {
			str = mapper.writeValueAsString(map);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	public static Map<?, ?> stringToMap(String str) throws JsonParseException,
			JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		Map<?, ?> map = null;
		map = mapper.readValue(str, Map.class);
		System.out.println(map.size());
		Iterator<?> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			Object key = iterator.next();
		}
		return map;
	}

	public static void main(String[] args) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> amap = new HashMap<String, Object>();
		amap.put("a", 1);
		amap.put("b", 2);
		String str = mapper.writeValueAsString(amap);
		System.out.println("map=" + str);
		String s = "{ \"name\" : \"萧远山\", \"sex\" : \"男\", \"age\" : \"23\",\"address\" : \"河南郑州\"}";
		s = str;
		try {
			Map<?, ?> map = mapper.readValue(s, Map.class);
			System.out.println(map.size());
			Iterator<?> iterator = map.keySet().iterator();
			while (iterator.hasNext()) {
				Object key = iterator.next();
				// System.out.print(key+":");
				// System.out.println(map.get(key).toString());
			}
			System.out.println("map2=" + map);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}